<script>
import { h, provide, ref, watch } from "vue";

export default {
  name: "TzTabs",
  props: {
    modelValue: {
      type: String,
      default: "",
    },
  },
  emits: ["update:modelValue", "tab-click"],
  setup(props, { emit }) {
    const currentName = ref(props.modelValue || props.activeName || "0");

    const setCurrentName = (value) => {
      if (currentName.value === value) return;
      currentName.value = value;
      emit("update:modelValue", value);
    };

    const handleClick = (tabName, event) => {
      setCurrentName(tabName);
      emit("tab-click", tabName, event);
    };

    provide("rootTabs", {
      props,
      currentName,
    });

    watch(
      () => props.modelValue,
      (modelValue) => {
        setCurrentName(modelValue);
      }
    );

    return {
      handleClick,
      currentName,
    };
  },
  render() {
    const { handleClick, currentName } = this;

    const slotsList = this.$slots.default();
    const slotPropsList = slotsList.map((item) => item.props);

    const headerItems = slotPropsList.map((item) =>
      h(
        "view",
        {
          class: {
            "el-tabs__item": true,
            actived: item.name === currentName,
          },
          onClick: (e) => handleClick(item.name, e),
        },
        item.label
      )
    );

    const tabHeader = h("view", { class: "tz-tabs__header" }, headerItems);
    const panels = this.$slots?.default();
    const tabContent = h("view", { class: "tz-tabs__content" }, panels);
    return h("view", { class: "tz-tabs" }, [tabHeader, tabContent]);
  },
};
</script>

<style lang="scss">
.tz-tabs {
  width: 100%;
  .tz-tabs__header {
    display: flex;
    .el-tabs__item {
      flex-grow: 1;
      border: 1px solid #ccc;
      height: 50px;
      line-height: 50px;
      text-align: center;
      &:not(:last-child) {
        border-right: 0;
      }
    }
    .actived {
      color: $primary-color-active;
      border-bottom: 2px solid $primary-color-active;
    }
  }
  .tz-tabs__content {
    padding: 10px 0;
  }
}
</style>
